package com.demo.springbootdemo.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.extension.toolkit.Db;
import com.demo.springbootdemo.domain.dto.PageDTO;
import com.demo.springbootdemo.domain.po.Address;
import com.demo.springbootdemo.domain.po.User;
import com.demo.springbootdemo.domain.query.UserQuery;
import com.demo.springbootdemo.domain.vo.AddressVO;
import com.demo.springbootdemo.domain.vo.UserVO;
import com.demo.springbootdemo.enums.UserStatus;
import com.demo.springbootdemo.mapper.UserMapper;
import com.demo.springbootdemo.service.IUserService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Override
    public void updateBalanceByIds(List<Long> ids, int amount) {
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<User>()
                .in(User::getId, ids);
        baseMapper.updateBalanceByIds(wrapper, amount);
    }

    @Override
    public void deductById(Long id, int money) {
        User user = this.getById(id);
        if (user == null) {
            throw new RuntimeException("用户状态异常");
        }
        if (user.getBalance() < money) {
            throw new RuntimeException("用户余额不足");
        }
        int remainBalance = user.getBalance() - money;
        /*baseMapper.deductById(id, money);*/
        lambdaUpdate()
                .set(User::getBalance, remainBalance)
                .set(remainBalance == 0, User::getStatus, UserStatus.FROZEN) // 余额清空冻结用户
                .eq(User::getId, id);
    }

    @Override
    public List<User> queryUsers(String name, Integer status, Integer minBalance, Integer maxBalance) {
        return lambdaQuery()
                .like(name != null, User::getUsername, name)
                .eq(status !=null, User::getStatus, status)
                .ge(minBalance != null, User::getBalance, minBalance)
                .le(maxBalance != null, User::getBalance, maxBalance)
                .list();
    }

    @Override
    public UserVO getByIdWithAddressList(Long id) {
        User user = getById(id);
        if (user == null || user.getStatus() == UserStatus.FROZEN) {
            throw new RuntimeException("用户状态异常");
        }
        List<Address> addressList = Db.lambdaQuery(Address.class)
                .eq(Address::getUserId, id)
                .list();
        UserVO userVO = BeanUtil.copyProperties(user, UserVO.class);
        if (CollUtil.isNotEmpty(addressList)) {
            userVO.setAddressList(BeanUtil.copyToList(addressList, AddressVO.class));
        }
        return userVO;
    }

    @Override
    public List<UserVO> listByIdsWithAddressList(List<Long> ids) {
        List<User> users = listByIds(ids);
        if (CollUtil.isEmpty(users)) {
            return Collections.emptyList();
        }
        List<Address> addresses = Db.lambdaQuery(Address.class)
                .in(Address::getUserId, ids)
                .list();
        List<AddressVO> addressVOS = BeanUtil.copyToList(addresses, AddressVO.class);
        Map<Long, List<AddressVO>> collect = addressVOS.stream().collect(Collectors.groupingBy(AddressVO::getUserId));

        List<UserVO> userVOS = new ArrayList<>(users.size());
        for (User user: users) {
            UserVO userVO = BeanUtil.copyProperties(user, UserVO.class);
            userVO.setAddressList(collect.get(user.getId()));
            userVOS.add(userVO);
        }
        return userVOS;
    }

    @Override
    public PageDTO<UserVO> queryUsersPage(UserQuery userQuery) {

        String name = userQuery.getName();
        Integer status = userQuery.getStatus();
        Integer minBalance = userQuery.getMinBalance();
        Integer maxBalance = userQuery.getMaxBalance();


        Page<User> userPage = lambdaQuery()
                .like(name != null, User::getUsername, name)
                .eq(status !=null, User::getStatus, status)
                .ge(minBalance != null, User::getBalance, minBalance)
                .le(maxBalance != null, User::getBalance, maxBalance)
                .page(userQuery.toMpPage());

//        return PageDTO.of(userPage, UserVO.class);
        return PageDTO.of(userPage, user -> BeanUtil.copyProperties(user, UserVO.class));
    }
}
